#include <pthread.h>
#include <unistd.h>

#include "jb_nanosic.h"
#include "nano_remote_processor.h"
#include "CLogcat.h"

int isProcessing = 0;
int mLastKeyCode = 0;

process_callback_p mPcb;

void nanoDataCb(char *pBuf, int length) {
    if (mPcb) {
        mPcb->onProcessBuffer((unsigned char *) pBuf, length);
    }
}

void nanoKeyCb(unsigned int action) {
    LOGD("nanoKeyCb action = %d \n", action);
    if (mPcb) {
        if (action) {
            mLastKeyCode = action;
            mPcb->onProcessKeyEvent(action, 1);
        } else {
            mPcb->onProcessKeyEvent(mLastKeyCode, 0);
        }
    }
}

int nano_ble_deviceState() {
//    return deviceState;
    int connect = Nano_Connected();
    LOGD("nano_ble_deviceState connect = %d", connect);
    //connect same time always 0;
    return connect;
}

int nano_rmt_init(process_callback_p pcb, int remoteType) {
    LOGD("+ nano_rmt_init ");
    if (isProcessing) {
        LOGD("nano remote already init");
        return 0;
    }

    if (pcb) {
        mPcb = pcb;
    } else {
        return -1;
    }

    int ret = Nano_Open();
    if (ret) {
        LOGE("nano remote open err : %d", ret);
        return -10;
    }

    if (remoteType == NANO_BLE_NODE) {
        //check device connect state
        if (!Nano_Connected()) {
            LOGE("nano ble device not connect");
            nano_rmt_destroy();
            return -11;
        }
    }

    //register callback
    Nano_RegisterDataReceivedCb(nanoDataCb);
    Nano_RegisterVoiceKeyCb(nanoKeyCb);

    isProcessing = 1;
    LOGD("- nano_rmt_init ");
    return 0;
}

int nano_hid_process(char *buf, int len) {
    if (mPcb) {
        Nano_appProcUsbData(buf, (char) len);
    }
    return 0;
}

int nano_rmt_destroy() {
    LOGD("nano_rmt_destroy ");
    Nano_Close();
    isProcessing = 0;
    return 0;
}

